package com.example.administrator.hqq.activity.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.alertview.AlertView;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.View.alertview.OnItemClickListener;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.GroupEvent;
import com.example.administrator.hqq.bean.JoinIntrrductionBean;
import com.example.administrator.hqq.bean.QNTokenBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.CameraUtils;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.example.administrator.hqq.utils.SketchTextWatcher;
import com.example.administrator.hqq.utils.UploadManagerUtils;
import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class SettingGroupActivity extends MyActivity {
    @BindView(R.id.join_group)
    ImageView joinGroup;
    @BindView(R.id.group_title)
    TextView groupTitle;
    @BindView(R.id.title_compile)
    ImageView titleCompile;
    @BindView(R.id.group_number)
    TextView groupNumber;
    @BindView(R.id.group_people)
    TextView groupPeople;
    @BindView(R.id.group_introduce)
    EditText groupIntroduce;
    @BindView(R.id.introduce_compile)
    ImageView introduceCompile;
    @BindView(R.id.group_question1)
    EditText groupQuestion1;
    @BindView(R.id.group_question2)
    EditText groupQuestion2;
    @BindView(R.id.join)
    Button join;
    @BindView(R.id.back)
    AutoLinearLayout back;
    @BindView(R.id.q1)
    TextView q1;
    @BindView(R.id.question_1)
    AutoLinearLayout question1;
    @BindView(R.id.question_2)
    AutoLinearLayout question2;
    @BindView(R.id.group_join_view1)
    View groupJoinView1;
    private String TAG = this.getClass().getSimpleName();
    private Boolean aBoolean;
    private String type;
    private AlertView photoAlertView;
    private QNTokenBean qnTokenBean;
    private String url;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_group);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        type = getIntent().getStringExtra(LoongsConfig.type);
        initview();
        initdata();
    }

    private void initview() {
        groupTitle.clearFocus();
        if (!TextUtils.isEmpty(type) || "member".equals(type)) {
            groupIntroduce.setEnabled(false);
            groupIntroduce.setFocusable(false);
            groupIntroduce.setKeyListener(null);
            groupQuestion1.setEnabled(false);
            groupQuestion1.setFocusable(false);
            groupQuestion1.setKeyListener(null);
            groupQuestion2.setEnabled(false);
            groupQuestion2.setFocusable(false);
            groupQuestion2.setKeyListener(null);
            join.setVisibility(View.GONE);
            introduceCompile.setVisibility(View.GONE);
        }
        SketchTextWatcher sketchTextWatcher1 = new SketchTextWatcher(groupQuestion1, 45);
        groupQuestion1.addTextChangedListener(sketchTextWatcher1);
        SketchTextWatcher sketchTextWatcher2 = new SketchTextWatcher(groupQuestion2, 45);
        groupQuestion2.addTextChangedListener(sketchTextWatcher2);
        groupIntroduce.addTextChangedListener(new SketchTextWatcher(groupIntroduce, 260 * 3));
    }
    private void initdata() {
        OkHttpUtils.get().url(UrlFactory.getJoinIntroduction())
                .addParams(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
                ToastUtils.showShort("数据访问错误");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                Gson gson = new Gson();
                join.setVisibility(View.VISIBLE);
                JoinIntrrductionBean joinIntrrductionBean = gson.fromJson(response, JoinIntrrductionBean.class);
                if (joinIntrrductionBean != null && joinIntrrductionBean.getCode() == 200) {
                    aBoolean = false;
                    if (!TextUtils.isEmpty(type) || "member".equals(type)){
                        if (joinIntrrductionBean.getQuestion_amount() == 1)
                        {
                            question2.setVisibility(View.GONE);
                            groupJoinView1.setVisibility(View.GONE);
                            join.setVisibility(View.GONE);
                        }
                    }
                    groupQuestion1.setText(joinIntrrductionBean.getQuestion_1());
                    if (joinIntrrductionBean.getQuestion_amount() == 2) {
                        groupQuestion2.setText(joinIntrrductionBean.getQuestion_2());
                    }
                    setMessage(joinIntrrductionBean);
                } else if (joinIntrrductionBean.getCode() == 201) {
                    aBoolean = true;
                    join.setText("完成");
                    if (!TextUtils.isEmpty(type) || "member".equals(type)) {
                        groupQuestion1.setVisibility(View.GONE);
                        question2.setVisibility(View.GONE);
                        q1.setText("该群暂无问题");
                        groupJoinView1.setVisibility(View.GONE);
                        join.setVisibility(View.GONE);
                    }
                    setMessage(joinIntrrductionBean);
                }
            }
        });
    }

    private void setMessage(JoinIntrrductionBean joinIntrrductionBean) {
        groupTitle.setText(joinIntrrductionBean.getTitle());
        groupNumber.setText(joinIntrrductionBean.getNumber());
        groupPeople.setText(joinIntrrductionBean.getMember_amount() + "/" + joinIntrrductionBean.getMax_member());
        if (!TextUtils.isEmpty(joinIntrrductionBean.getIntroduction())) {
            groupIntroduce.setText(joinIntrrductionBean.getIntroduction());
        } else {
            if (!TextUtils.isEmpty(type) || "member".equals(type)) {
                groupIntroduce.setText("此群暂无介绍");
            }else{
                groupIntroduce.setHint("请输入群介绍");
            }

        }
        Glide.with(this).load(joinIntrrductionBean.getUrl()).centerCrop().into(joinGroup);
    }

    @OnClick({R.id.join_group,R.id.title_compile, R.id.introduce_compile, R.id.join, R.id.back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.join_group:
                if (!TextUtils.isEmpty(type) || "member".equals(type))
                {
                    return;
                }
                photoAlertView = AlertViewFactory.getInstance().getPhotoAlertView(this, new OnItemClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == -1) {
                            photoAlertView.dismiss();
                        } else if (position == 2) {
                            url = "system_group_v1";
                            Glide.with(SettingGroupActivity.this)
                                    .load(R.drawable.system_group_v1)
                                    .centerCrop()
                                    .into(joinGroup);
                        } else if (position == 0) {
                            SettingGroupActivityPermissionsDispatcher.startLocationWithCheck(SettingGroupActivity.this);
                        } else if (position == 1) {
                            SettingGroupActivityPermissionsDispatcher.startStorageWithCheck(SettingGroupActivity.this);
                        }
                    }
                });
                photoAlertView.show();
                break;
//           case R.id.question_compile:
//               groupQuestion1.requestFocus();
//              break;
            case R.id.introduce_compile:
                groupIntroduce.requestFocus();
                break;
            case R.id.title_compile:
                groupTitle.requestFocus();
                break;
            case R.id.join:
                setGroupInfo();
                if (!TextUtils.isEmpty(url)){
                    setGroupUrl();
                }
                break;
        }
    }

    private void setGroupUrl() {
        OkHttpUtils.get().url(UrlFactory.setGroupUrl())
                .addParams(LoongsConfig.user_id,LoongsConfig.getUser_id())
                .addParams(LoongsConfig.group_id,getIntent().getStringExtra(LoongsConfig.group_id))
                .addParams(LoongsConfig.url,url)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "修改群头像onError: "+e.getMessage() );
                if (aBoolean)
                {
                    finish();
                }
                aBoolean=true;
            }
            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "修改群头像onResponse: "+response );
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {
                        GroupEvent groupEvent = new GroupEvent();
                        groupEvent.setType(GroupEvent.Type.ALTER_GROUP);
                        EventBus.getDefault().post(groupEvent);
                    }
                    if (aBoolean)
                    {
                        finish();
                    }
                    aBoolean=true;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
}

    private void setGroupInfo() {
        String groupQusetion = "";
        int groupQusetionnumber = 0;
        if (!TextUtils.isEmpty(groupQuestion1.getText().toString())) {
            groupQusetionnumber++;
            groupQusetion += groupQuestion1.getText().toString();
        }
        if (!TextUtils.isEmpty(groupQuestion2.getText().toString())) {
            if (!TextUtils.isEmpty(groupQuestion1.getText().toString()))
            {
                groupQusetionnumber++;
                groupQusetion += "/*@*/"+groupQuestion2.getText().toString();
            }else{
                groupQusetionnumber++;
                groupQusetion += groupQuestion2.getText().toString();
            }
        }
        GetBuilder url = OkHttpUtils.get().url(UrlFactory.setJoinIntroduction());
        url.addParams(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id))
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.introduction, groupIntroduce.getText().toString() + "")
                .addParams(LoongsConfig.question_amount, groupQusetionnumber + "")
                .addParams(LoongsConfig.question, groupQusetion)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "设置群信息onError: " + e.getMessage());
                if (TextUtils.isEmpty(SettingGroupActivity.this.url))
                {
                    finish();
                }else{
                    if (aBoolean)
                    {
                        finish();
                    }
                    aBoolean=true;
                }
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "设置去信息onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code),jsonObject.getString(LoongsConfig.description));
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {
                        GroupEvent groupEvent = new GroupEvent();
                        groupEvent.setType(GroupEvent.Type.ALTER_GROUP);
                        EventBus.getDefault().post(groupEvent);
                        if (TextUtils.isEmpty(SettingGroupActivity.this.url))
                        {
                            finish();
                        }else{
                            if (aBoolean)
                            {
                                finish();
                            }
                            aBoolean=true;
                        }
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CameraUtils.getInstance().onActivityResult(this, requestCode, resultCode, data, new CameraUtils.OnResultListener() {
            @Override
            public void takePhotoFinish(String path) {
                File picFile = new File(path);
                if (picFile.exists()) {
                    CameraUtils.getInstance().cropPicture(SettingGroupActivity.this, path, 7, 3,false,100);//裁剪图片
                }
            }

            @Override
            public void selectPictureFinish(String path) {
                File picFile = new File(path);
                if (picFile.exists()) {
                    CameraUtils.getInstance().cropPicture(SettingGroupActivity.this, path, 7, 3,false,100);//裁剪图片
                }
            }

            @Override
            public void cropPictureFinish(String path) {
                getQNToken(path);
            }
        });
    }
    public void getQNToken(String path) {
        showLoadingDialog();
        final File picFile = new File(path);
        OkHttpUtils.get().url(UrlFactory.getQNToken())
                .addParams(LoongsConfig.id, getIntent().getStringExtra(LoongsConfig.group_id))
                .addParams(LoongsConfig.type, LoongsConfig.GROUP)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                aBoolean=true;
                Log.e(TAG, "onError: " + e.getMessage());
                dismissLoadingDialog();
            }

            @Override
            public void onResponse(String s, int id) {

                Log.e(TAG, "onResponse: " + s);
                final Gson gson = new Gson();
                qnTokenBean = gson.fromJson(s, QNTokenBean.class);
                if (qnTokenBean.getCode() == 200)
                    UploadManagerUtils.getUploadManager().put(picFile, qnTokenBean.getKey(), qnTokenBean.getToken(), new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            if (info.isOK()) {
                                Log.i("qiniu", "res");
                                Glide.with(SettingGroupActivity.this)
                                        .load(qnTokenBean.getUrl())
                                        .centerCrop()
                                        .into(joinGroup);
                                url = qnTokenBean.getId();
                            } else {

                            }
                            dismissLoadingDialog();
                            Log.e("qiniu", key + ", " + info + ", " + res);
                        }
                    }, null);
            }
        });
    }
    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(String s) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    /**
     * 申请权限
     */
    @SuppressLint("NoCorrespondingNeedsPermission")
    @OnShowRationale({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForLocation(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("申请相机权限")
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForLocation() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForLocation() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void startLocation() {
        CameraUtils.getInstance().takeCamera(this);
    }

    @OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showRetionaleForStorage(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.storage_permission))
                .setPositiveButton(getString(R.string.agree), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton(getString(R.string.refuse), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnNeverAskAgain(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showNeverAskForStorage() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showDeniedForStorage() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    public void startStorage() {
        CameraUtils.getInstance().openAlbum(this);
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SettingGroupActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

}
